<template>
	<view class="app-system-pay-layout-form" :style="[AppSkinVar]">
		<goods-layout-form
			ref="goodsLayoutFormRef"
			v-model:value="goodsFormAnswerList"
			:info="layoutFormData"
			:price="0"
			:number="0"
			@priceChange="handlePriceChange"
			v-if="layoutFormData"
		></goods-layout-form>
		<view class="app-system-pay-layout-form__footer fixed-bottom bg-white e-flex e-flex-between">
			<view class="fw-500">
				<text>{{ $t('common.totalPrice') }}{{ $t('common.:') }}</text>
				<text class="c-red">{{ global.unitEn }}{{ priceFormat(totalPrice || 0, 2) }}</text>
			</view>
			<view class="app-system-pay-layout-form__btn bg-primary e-flex-xy-center" @click="handleSubmitGoodsForm">
				<text class="c-white fw-500">{{ $t('order.提交') }}</text>
			</view>
		</view>
		<pay-popup ref="payPopup" storeType="1" :payMoney="totalPrice" v-model:show="payShow" @close="payShow = false" @pay="handlePay"></pay-popup>
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { getSystemLayoutFormJson, postSystemLayoutFormBrowse, postSubmitSystemLayoutForm, getLayoutFormPayResult } from '@/common/request/api';
import type { GoodsForm, FormCartParams } from '@/common/request/api';
import type { LayoutFormModelValue, GoodsLayoutFormInstance } from '@/typings';
import { priceFormat, isString } from '@/common/utils';
import { useCurrentInstance } from '@/common/hooks';
import { usePay } from '../hooks/usePay';
import { useGlobal } from '@/common/stores';
import { storeToRefs } from 'pinia';
import { onLoad } from '@dcloudio/uni-app';

const props = defineProps<{
	id: string;
}>();
const ctx = useCurrentInstance();
const { systemPay, getH5PayResult } = usePay();
const { global } = storeToRefs(useGlobal());

const layoutFormData = ref<GoodsForm>();

const goodsLayoutFormRef = ref<GoodsLayoutFormInstance>();
const goodsFormAnswerList = ref<LayoutFormModelValue>([]);

const totalPrice = ref(0);
const handlePriceChange = (e: number) => {
	totalPrice.value = e;
};
let formAnswerList: FormCartParams['list'] = [];
const payShow = ref(false);

const handleSubmitGoodsForm = async () => {
	const res = await goodsLayoutFormRef.value?.validate?.();
	if (!res) {
		return;
	}
	const submitList = goodsFormAnswerList.value.map((item) => {
		let formOptionsInfoId = isString(item.formOptionsInfoId) ? item.formOptionsInfoId : item.formOptionsInfoId?.join?.(',') || '';
		return {
			formOptionsId: item.formOptionsId,
			formOptionsInfoIdText: item.formOptionsInfoIdText,
			formOptionsInfoId,
			vle: (item.fileList?.length ? JSON.stringify(item.fileList) : item.vle) || formOptionsInfoId
		};
	});
	postSystemLayoutFormBrowse({
		subType: 1,
		formId: props.id,
		list: submitList
	}).then((res) => {
		if (res.data.subFormDto.totalPrice > 0) {
			totalPrice.value = res.data.subFormDto.totalPrice;
			formAnswerList = submitList;
			payShow.value = true;
		} else {
			postSubmitSystemLayoutForm(params).then(() => {
				ctx.$toastAndBack(ctx.$t('tools.submitSuccess'))
			});
		}
	});
};
const handlePay = async (payId: number, payword: string | undefined = undefined, payType: PayType) => {
	payShow.value = false;
	const res = await postSubmitSystemLayoutForm({
		payId,
		fromType: getApp<UniGlobalData>().globalData?.payFromType,
		payword,
		subType: 1,
		formId: props.id,
		list: formAnswerList
	});
	await systemPay({
		payType,
		resolveData: res,
		payParams: res.data,
		api: getLayoutFormPayResult,
		storageKey: 'payTimeCardOrderId',
		orderIdKey: 'paycode',
		payMoney:totalPrice.value,
		successUrl: () => 'systemPay/layoutForm/success',
		errorUrl: (msg: string) => `systemPay/layoutForm/error?msg=${msg}`
	});
};

getH5PayResult('', 'paySystemLayoutFormOrderId', getLayoutFormPayResult);

onLoad(() => {
	getSystemLayoutFormJson({ formId: props.id }).then((res) => {
		goodsFormAnswerList.value = res.data.formOptions.map((item) => {
			return {
				formOptionsId: item.id,
				formOptionsInfoId: [4, 5].includes(item.type) ? [] : '',
				formOptionsInfoIdText: '',
				vle: '',
				fileList: item.type === 6 ? [] : undefined,
				vleid: item.vleid
			};
		});
		layoutFormData.value = res.data;
		uni.setNavigationBarTitle({
			title: res.data.title
		});
	});
});
</script>

<style lang="scss" scoped>
@include appBem_b(system-pay-layout-form) {
	padding-bottom: 110rpx;
	:deep(.app-components-goods-layout-form) {
		min-height: 100vh;
	}
	@include appBem_e(btn) {
		min-width: 360rpx;
		height: 90rpx;
		border-radius: 2rpx;
		padding: 0 20rpx;
	}

	@include appBem_e(footer) {
		height: 110rpx;
		padding: 0 20rpx;
	}
}
</style>
